package com.sailing.xjpb.ipaas.client.common;

import com.sailing.xjpb.common.exception.AuthorizeException;
import com.sailing.xjpb.common.exception.IpaasClientException;
import com.sailing.xjpb.common.web.ResponseCode;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Ipaas RestTemplate访问出错的错误处理器
 *
 * @author YaoWei
 * createDate: 2020/12/3 18:10
 */
@Slf4j
public class IpaasClientResponseErrorHandler extends DefaultResponseErrorHandler {

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        HttpStatus statusCode = HttpStatus.resolve(response.getRawStatusCode());
        byte[] body = getResponseBody(response);
        Charset charset = getCharset(response);
        String errorMsg = new String(body, charset);
        if (statusCode == HttpStatus.UNAUTHORIZED) {
            log.error("ipaas用户认证失败：{}", errorMsg);
            throw new AuthorizeException("用户未登录或登录信息已过期！", new AuthorizeException(errorMsg));
        } else {
            throw new IpaasClientException(ResponseCode.T_4000, "ipaas接口异常：" + errorMsg);
        }
    }

    @NonNull
    @Override
    protected Charset getCharset(@NonNull ClientHttpResponse response) {
        Charset charset = super.getCharset(response);
        return charset == null ? StandardCharsets.UTF_8 : charset;
    }

}
